package com.vrv.vap.baseline.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.vrv.vap.baseline.entity.VisualDashboard;
import com.vrv.vap.baseline.mapper.VisualDashboardMapper;
import com.vrv.vap.baseline.util.FileOperationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Service
public class VisualDashboardImportService {
    private static final Logger log = LoggerFactory.getLogger(VisualDashboardImportService.class);
    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");

    @Autowired
    private VisualDashboardMapper visualDashboardMapper;

    @Autowired
    private FileOperationUtil fileOperationUtil;

    /**
     * 处理导入ZIP文件
     * @param file 上传的ZIP文件
     * @return 导入的记录数
     * @throws IOException 如果文件处理过程中发生错误
     */
    @Transactional(rollbackFor = Exception.class)
    public int importFromZip(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }

        // 创建临时目录用于解压文件
        String extractDir = TEMP_DIR + File.separator + UUID.randomUUID().toString();
        Path extractPath = Paths.get(extractDir);
        Files.createDirectories(extractPath);

        try {
            // 解压ZIP文件
            List<String> excelFiles = extractZipFile(file, extractPath);
            if (excelFiles.isEmpty()) {
                throw new IllegalArgumentException("ZIP文件中没有找到Excel文件");
            }

            // 处理所有Excel文件并导入数据
            int totalImported = 0;
            for (String excelFile : excelFiles) {
                totalImported += importFromExcel(excelFile);
            }

            return totalImported;
        } finally {
            // 清理临时文件
            fileOperationUtil.deleteDirectory(extractPath.toFile());
        }
    }

    /**
     * 解压ZIP文件并返回所有Excel文件的路径
     * @param zipFile ZIP文件
     * @param extractPath 解压目标路径
     * @return Excel文件路径列表
     * @throws IOException 如果解压过程中发生错误
     */
    private List<String> extractZipFile(MultipartFile zipFile, Path extractPath) throws IOException {
        List<String> excelFiles = new ArrayList<>();

        try (ZipInputStream zipInputStream = new ZipInputStream(zipFile.getInputStream())) {
            ZipEntry entry;
            while ((entry = zipInputStream.getNextEntry()) != null) {
                if (!entry.isDirectory() && (entry.getName().endsWith(".xlsx") || entry.getName().endsWith(".xls"))) {
                    String filePath = extractPath.resolve(entry.getName()).toString();
                    Files.copy(zipInputStream, Paths.get(filePath));
                    excelFiles.add(filePath);
                }
            }
        }

        return excelFiles;
    }

    /**
     * 从Excel文件导入数据
     * @param excelFilePath Excel文件路径
     * @return 导入的记录数
     */
    private int importFromExcel(String excelFilePath) {
        final int[] importedCount = {0};

        EasyExcel.read(excelFilePath, VisualDashboard.class, new PageReadListener<VisualDashboard>((dataList) -> {
            for (VisualDashboard visualDashboard : dataList) {
                if (isValidData(visualDashboard)) {
                    try {
                        // 检查记录是否存在
                        VisualDashboard existing = visualDashboardMapper.selectById(visualDashboard.getId());
                        if (existing != null) {
                            visualDashboardMapper.update(visualDashboard);
                        } else {
                            visualDashboardMapper.insert(visualDashboard);
                        }
                        importedCount[0]++;
                    } catch (Exception e) {
                        log.error("导入数据失败: {}", visualDashboard, e);
                    }
                }
            }
        })).sheet().doRead();

        return importedCount[0];
    }

    /**
     * 验证数据有效性
     * @param visualDashboard 可视化仪表盘对象
     * @return 数据是否有效
     */
    private boolean isValidData(VisualDashboard visualDashboard) {
        return visualDashboard != null && visualDashboard.getId() != null;
    }
}